package com.server.questionbank.snframe.util.FileUtil.operation.command;

import com.server.questionbank.snframe.util.FileUtil.operation.base.AbstractOperation;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件下载命令
 */
@Slf4j
public class DownloadCommand extends AbstractOperation<Void> {
    private final File targetFile;
    private final boolean overwrite;
    
    public DownloadCommand(MinioClient minioClient, String bucket, String object, 
            File targetFile, boolean overwrite) {
        super(minioClient, bucket, object);
        this.targetFile = targetFile;
        this.overwrite = overwrite;
    }
    
    @Override
    protected Void doExecute() throws Exception {
        // 检查目标文件
        if (targetFile.exists() && !overwrite) {
            throw new IllegalStateException("Target file already exists: " + targetFile.getAbsolutePath());
        }
        
        // 确保目标目录存在
        File parentDir = targetFile.getParentFile();
        if (!parentDir.exists() && !parentDir.mkdirs()) {
            throw new IllegalStateException("Failed to create directory: " + parentDir.getAbsolutePath());
        }
        
        // 执行下载
        try (InputStream is = minioClient.getObject(
                GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(object)
                    .build());
             OutputStream os = new FileOutputStream(targetFile)) {
            
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            
            return null;
        }
    }
    
    @Override
    public void validate() {
        super.validate();
        if (targetFile == null) {
            throw new IllegalArgumentException("Target file cannot be null");
        }
    }
} 